package com.cgnpc.scp.hse.controller;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.cgnpc.cud.annotation.OperatorType;
import com.cgnpc.cud.annotation.UBA;
import com.cgnpc.cud.boot.autoconfigure.aep.AepProperties;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.bean.CreateFileInfo;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.mybatis.entity.ScpCommonSmsInfo;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.service.IScpCommonSmsInfoService;
import com.cgnpc.scp.common.service.SmsCenterService;
import com.cgnpc.scp.common.utils.AjaxResultUtil;
import com.cgnpc.scp.common.utils.ListUtil;
import com.cgnpc.scp.hse.mybatis.entity.HseMeetingInfo;
import com.cgnpc.scp.hse.mybatis.entity.HseMeetingUser;
import com.cgnpc.scp.hse.service.IHseMeetingInfoService;
import com.cgnpc.scp.hse.service.IHseMeetingUserService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/******************************
 * 用途说明: 调试HSE管理-会议信息
 * 作者姓名: yblrs
 * 创建时间: 2020/8/20 22:20
 ******************************/
@Controller
@RequestMapping("/scp/hse/meetingInfo")
public class HseMeetingInfoController {
    private static final Logger LOGGER = LoggerFactory.getLogger(HseMeetingInfoController.class);

    @Autowired
    private CurrentUser currentUser;

    @Autowired
    private IHseMeetingInfoService hseMeetingInfoService;

    @Autowired
    private IHseMeetingUserService hseMeetingUserService;

    @Autowired
    private AepProperties aepProperties;

    @Autowired
    private SmsCenterService smsCenterService;

    @Autowired
    private IScpCommonSmsInfoService scpCommonSmsInfoService;

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---分页查询
     * 参数说明: HttpServletRequest request, @RequestBody T reqEntity
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试HSE管理-会议信息---分页查询")
    @UBA(module = "调试HSE管理", action = "会议分页查询", channel = OperatorType.Page)
    @RequestMapping(value = "/loadByPaging", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends HseMeetingInfo> Object loadByPaging(HttpServletRequest request, @RequestBody T reqEntity) {
        AjaxResult ajaxResult = null;

        try {
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            MyPageResult<T> myPageResult = hseMeetingInfoService.loadByPaging(loginUserInfo, reqEntity);
            ajaxResult = AjaxResultUtil.createSuccessMessage(myPageResult);
        } catch (Exception e) {
            LOGGER.error("loadByPaging.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---保存或修改
     * 参数说明: HttpServletRequest request, @RequestBody List<T> reqEntityList
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试HSE管理-会议信息---保存或修改")
    @UBA(module = "调试HSE管理", action = "保存修改会议", channel = OperatorType.Button)
    @RequestMapping(value = "/saveOrUpdate", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends HseMeetingInfo> Object saveOrUpdate(HttpServletRequest request, @RequestBody List<T> reqEntityList) {
        AjaxResult ajaxResult = null;

        try {
            // 获取当前的登录用户信息
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            // 获取请求的语言reqLocale，cookie需要包含lang=cn，或者lang=en
            Locale reqLocale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);

            ajaxResult = hseMeetingInfoService.saveOrUpdate(loginUserInfo, reqLocale, reqEntityList);
            Object objData = ajaxResult == null ? null : ajaxResult.get(AjaxResultUtil.KEY_DATA);

            // begin 判断结果并发送短信
            if (objData instanceof List) {
                List dataList = (List) objData;

                for (Object dataListItem : dataList) {
                    try {
                        if (dataListItem instanceof HseMeetingInfo) {
                            HseMeetingInfo hseMeetingInfo = (HseMeetingInfo) dataListItem;
                            String hseMeetingInfoId = hseMeetingInfo.getId();
                            ScpCommonSmsInfo scpCommonSmsInfo = hseMeetingInfoService.sendSmsMessage(hseMeetingInfoId);
                            ApiResult smsCenterApiResult = smsCenterService.sendSmsToSmsCenter(scpCommonSmsInfo);
                            scpCommonSmsInfoService.updateSmsSend(scpCommonSmsInfo.getId(), smsCenterApiResult);
                        }
                    } catch (Exception e) {
                        LOGGER.error("error", e);
                    }
                }
            }
            // end 判断结果并发送短信
        } catch (Exception e) {
            LOGGER.error("saveOrUpdate.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---导出Excel
     * 参数说明: HttpServletRequest request, @RequestBody T reqEntity
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试HSE管理-会议信息---导出Excel")
    @UBA(module = "调试HSE管理", action = "会议信息导出Excel", channel = OperatorType.Button)
    @RequestMapping(value = "/exportExcel", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends HseMeetingInfo> Object exportExcel(HttpServletRequest request, @RequestBody T reqEntity) {
        AjaxResult ajaxResult = null;

        try {
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            CreateFileInfo createFileInfo = hseMeetingInfoService.exportExcel(loginUserInfo, reqEntity);
            ajaxResult = AjaxResultUtil.createSuccessMessage(createFileInfo);
        } catch (Exception e) {
            LOGGER.error("exportExcel.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---根据会议id查询会议信息
     * 参数说明: HttpServletRequest request, @RequestBody T reqEntity
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试HSE管理-会议信息---根据会议id查询会议信息")
    @UBA(module = "调试HSE管理", action = "查看会议详细信息", channel = OperatorType.Button)
    @RequestMapping(value = "/queryById", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends HseMeetingInfo> Object queryById(HttpServletRequest request, @RequestBody T reqEntity) {
        AjaxResult ajaxResult = null;

        try {
            T resultEntity = hseMeetingInfoService.queryById(reqEntity);
            ajaxResult = AjaxResultUtil.createSuccessMessage(resultEntity);
        } catch (Exception e) {
            LOGGER.error("queryById.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---根据会议id删除会议信息
     * 参数说明: HttpServletRequest request, @RequestBody T reqEntity
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试HSE管理-会议信息---根据会议id删除会议信息")
    @UBA(module = "调试HSE管理", action = "删除会议", channel = OperatorType.Button)
    @RequestMapping(value = "/deleteById", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends HseMeetingInfo> Object deleteById(HttpServletRequest request, @RequestBody T reqEntity) {
        AjaxResult ajaxResult = null;

        try {
            // 获取当前的登录用户信息
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            // 获取请求的语言reqLocale，cookie需要包含lang=cn，或者lang=en
            Locale reqLocale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);

            ajaxResult = hseMeetingInfoService.deleteById(loginUserInfo, reqLocale, reqEntity);
        } catch (Exception e) {
            LOGGER.error("deleteById.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---系统定时开始会议
     * 参数说明:
     * 返回值说明: void
     ***********************************/
    @Scheduled(cron = "0 */5 * * * ?") // 每5分钟执行一次
    // @Scheduled(cron = "0/5 * * * * ?") // 每5秒执行一次
    public <T extends HseMeetingInfo> void autoStartMeeting() {
        try {
            final int pageSize = 1000;
            int pageNum = 0;
            boolean hasNext = true;
            final boolean timerAutoRun = true;

            while (hasNext) {
                pageNum++;
                List<T> dbMeetingInfoList = hseMeetingInfoService.queryNeedStartList(pageNum, pageSize);
                int dbMeetingInfoListSize = ListUtil.getListSizeWith0(dbMeetingInfoList);

                if (dbMeetingInfoListSize <= 0) {
                    hasNext = false;
                    return;
                }

                hasNext = dbMeetingInfoListSize >= pageSize;

                for (T dbMeetingInfo : dbMeetingInfoList) {
                    try {
                        hseMeetingInfoService.startMeetingInfo(null, null, dbMeetingInfo.getId(), timerAutoRun);
                    } catch (Exception e) {
                        LOGGER.error("autoStartMeeting.error;", e);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("autoStartMeeting.error;", e);
        }
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---系统定时结束会议
     * 参数说明:
     * 返回值说明: void
     ***********************************/
    @Scheduled(cron = "0 */5 * * * ?") // 每5分钟执行一次
    // @Scheduled(cron = "0/5 * * * * ?") // 每5秒执行一次
    public <T extends HseMeetingInfo> void autoEndMeeting() {
        try {
            final int pageSize = 1000;
            int pageNum = 0;
            boolean hasNext = true;
            final boolean timerAutoRun = true;

            while (hasNext) {
                pageNum++;
                List<T> dbMeetingInfoList = hseMeetingInfoService.queryNeedEndList(pageNum, pageSize);
                int dbMeetingInfoListSize = ListUtil.getListSizeWith0(dbMeetingInfoList);

                if (dbMeetingInfoListSize <= 0) {
                    hasNext = false;
                    return;
                }

                hasNext = dbMeetingInfoListSize >= pageSize;

                for (T dbMeetingInfo : dbMeetingInfoList) {
                    try {
                        hseMeetingInfoService.endMeetingInfo(null, null, dbMeetingInfo.getId(), timerAutoRun);
                    } catch (Exception e) {
                        LOGGER.error("autoEndMeeting.error;", e);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("autoEndMeeting.error;", e);
        }
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---开始会议
     * 参数说明: HttpServletRequest request, @RequestBody T reqEntity
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试HSE管理-会议信息---开始会议")
    @UBA(module = "调试HSE管理", action = "开始会议", channel = OperatorType.Button)
    @RequestMapping(value = "/startMeetingInfo", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends HseMeetingInfo> Object startMeetingInfo(HttpServletRequest request, @RequestBody T reqEntity) {
        AjaxResult ajaxResult = null;

        try {
            // 获取当前的登录用户信息
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            // 获取请求的语言reqLocale，cookie需要包含lang=cn，或者lang=en
            Locale reqLocale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);

            String reqEntityId = reqEntity.getId();

            ajaxResult = hseMeetingInfoService.startMeetingInfo(loginUserInfo, reqLocale, reqEntityId);
        } catch (Exception e) {
            LOGGER.error("startMeetingInfo.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---结束会议
     * 参数说明: HttpServletRequest request, @RequestBody T reqEntity
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试HSE管理-会议信息---结束会议")
    @UBA(module = "调试HSE管理", action = "结束会议", channel = OperatorType.Button)
    @RequestMapping(value = "/endMeetingInfo", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends HseMeetingInfo> Object endMeetingInfo(HttpServletRequest request, @RequestBody T reqEntity) {
        AjaxResult ajaxResult = null;

        try {
            // 获取当前的登录用户信息
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            // 获取请求的语言reqLocale，cookie需要包含lang=cn，或者lang=en
            Locale reqLocale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);

            String reqEntityId = reqEntity.getId();

            ajaxResult = hseMeetingInfoService.endMeetingInfo(loginUserInfo, reqLocale, reqEntityId);
        } catch (Exception e) {
            LOGGER.error("endMeetingInfo.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---取消会议
     * 参数说明: HttpServletRequest request, @RequestBody T reqEntity
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试HSE管理-会议信息---取消会议")
    @UBA(module = "调试HSE管理", action = "取消会议", channel = OperatorType.Button)
    @RequestMapping(value = "/cancelMeetingInfo", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends HseMeetingInfo> Object cancelMeetingInfo(HttpServletRequest request, @RequestBody T reqEntity) {
        AjaxResult ajaxResult = null;

        try {
            // 获取当前的登录用户信息
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            // 获取请求的语言reqLocale，cookie需要包含lang=cn，或者lang=en
            Locale reqLocale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);

            String reqEntityId = reqEntity.getId();

            ajaxResult = hseMeetingInfoService.cancelMeetingInfo(loginUserInfo, reqLocale, reqEntityId);
        } catch (Exception e) {
            LOGGER.error("cancelMeetingInfo.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议信息---发送短信
     * 参数说明:
     * 返回值说明: Object
     ***********************************/
    // @Scheduled(cron = "0 */5 * * * ?") // 每5分钟执行一次
    // @Scheduled(cron = "0/5 * * * * ?") // 每5秒执行一次
    public <T extends HseMeetingInfo> void autoNeedSendSms() {
        // 测试之后发现短信接口需要登录人信息，所以去掉定时器自动发送短信功能

        try {
            final int pageSize = 1000;
            int pageNum = 1;
            boolean hasNext = true;

            while (hasNext) {
                List<HseMeetingUser> dbHseMeetingUserList = hseMeetingUserService.queryNeedSendSms(pageNum, pageSize);
                int dbHseMeetingUserListSize = ListUtil.getListSizeWith0(dbHseMeetingUserList);
                hasNext = dbHseMeetingUserListSize >= pageSize;

                if (dbHseMeetingUserListSize <= 0) {
                    return;
                }

                List<String> usedHseMeetingInfoIdList = new ArrayList<>();

                for (HseMeetingUser dbHseMeetingUser : dbHseMeetingUserList) {
                    if (!usedHseMeetingInfoIdList.contains(dbHseMeetingUser.getMeetingInfoId())) {
                        usedHseMeetingInfoIdList.add(dbHseMeetingUser.getMeetingInfoId());
                    }
                }

                for (String usedHseMeetingInfoId : usedHseMeetingInfoIdList) {
                    try {
                        hseMeetingInfoService.sendSmsMessage(usedHseMeetingInfoId);
                    } catch (Exception e) {
                        LOGGER.error("needSendSms.error;", e);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("needSendSms.error;", e);
        }
    }

}
